package com.seo.textgen.caseanalyser;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.seo.textgen.pos.tagger.Token;

public class CaseAnalyser {

	private static final Pattern UPPERCASE_PATTERN = Pattern.compile("\\p{Lu}+");
	
	private Map<String, CaseStatistics> caseStatistics = new HashMap<String, CaseStatistics>();
	
	public void train(Token token, boolean startOfSentence) {
		CaseStatistics tokenCaseStatistics = caseStatistics.get(token.getTokenInLowerCase());
		if (tokenCaseStatistics == null) {
			tokenCaseStatistics = new CaseStatistics();
			caseStatistics.put(token.getTokenInLowerCase(), tokenCaseStatistics);
		}

		if (isOriginalCase(token.getToken())) {
			tokenCaseStatistics.incOriginal();
			return;
		}

		if (!startOfSentence) {
			if (UPPERCASE_PATTERN.matcher(token.getToken().subSequence(0, 1)).matches()) {
				tokenCaseStatistics.incCapitalized();
			} else {
				tokenCaseStatistics.incLower();
			}
		}
	}

	public String getTokenInProperCase(Token token) {
		CaseStatistics tokenCaseStatistics = caseStatistics.get(token.getTokenInLowerCase());
		if (tokenCaseStatistics.getLower() >= tokenCaseStatistics.getOriginal() && tokenCaseStatistics.getLower() >= tokenCaseStatistics.getCapitalized()) {
			return token.getTokenInLowerCase();
		}
		if (tokenCaseStatistics.getCapitalized() >= tokenCaseStatistics.getOriginal()) {
			return StringUtils.capitalize(token.getToken());
		}
		return token.getToken();
	}
	
	private boolean isOriginalCase(String token) {
		int upperCount = 0;
		for (int i = 0; i < token.length(); i++) {
			if (Character.isUpperCase(token.charAt(i))) {
				upperCount++;
				if (upperCount >= 2) {
					return true;
				}
			}
		}
		return false;
	}
	
	@Override
	public String toString() {
		return caseStatistics.toString();
	}
}
